package forum.logs;

import java.io.*;
import java.text.DateFormat;
import java.util.Date;


public class LogForum implements Serializable {
	
	public static void gravarErro(Exception exception) {
		try {
			File file = new File("log_forum.txt");
			
			if (!file.exists()) {
				file.createNewFile();
			}
			
			RandomAccessFile raf = new RandomAccessFile(file, "rw");
			raf.seek(raf.length());
			
			DateFormat format = DateFormat.getDateTimeInstance();
			String erro = LogForum.getMenssagemErro(exception);
			
			
			raf.writeBytes(String.format("%s\n", format.format(new Date()).toString()));
			raf.writeBytes(String.format("%s\n", erro));
			
			raf.writeBytes(String.format("\n%s\n\n", "----------------"));
			raf.close();
		} catch (Exception exception2) {
			exception2.printStackTrace();
		}
	}
	
	public static String getMenssagemErro(Exception exception) {
		StringBuilder sb = new StringBuilder();
		sb.append(exception.toString());
		sb.append("\n");
		
		for (StackTraceElement elemento : exception.getStackTrace()) {
			sb.append(elemento.toString());
			sb.append("\n");
		}
		
		return sb.toString();
	}
	
	public static void main(String[] args) {
		try {
			//Integer.valueOf("");
			int a = 2 / 0;
			System.out.println();
		} catch (Exception exception) {
			exception.printStackTrace();
			LogForum.gravarErro(exception);
		}
	}
}
